package com.qcxk.yuqian.system.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import com.qcxk.yuqian.system.entity.WordXmlBean;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

//import com.spire.doc.FileFormat;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class WordXmlUtil {

    @Value("${spring.servlet.exportWordPath}")
    private static String exportWordPath;
    @Value("${spring.servlet.exportWordUrl}")
    private static String exportWordUrl;

    public static WordXmlBean getXmlAndOptions(String wordType) {
        exportWordPath = "/Users/littleqiqi/Desktop/tmp/不要删/表单/yuqian";
        exportWordUrl = "http://127.0.0.1:80";
        if (StringUtils.isBlank(wordType)) {
            wordType = "0";
        }
        Map<String, List<String>> allOptions = new HashMap<String, List<String>>();
        String srcWordPath = exportWordPath;
        if ("0".equals(wordType)) {
            srcWordPath += "/北京航力安太购销合同（购销合同模板）.xml";
        }
//		if("0".equals(wordType)) {
//			List<String> serviceType_list = new ArrayList<String>(Arrays.asList(new String[] {"一次性伤残补助金", "一次性工伤医疗补助金", "一次性工亡补助金", null, "1-4级人员定期待遇", "供养亲属抚恤金", "丧葬补助金", "其它"}));
//			allOptions.put("serviceType_list", serviceType_list);
//
//			List<String> distributionMethod_list = new ArrayList<String>(Arrays.asList(new String[] {"单位发放", "市民卡发放"}));
//			allOptions.put("distributionMethod_list", distributionMethod_list);
//
//			List<String> remark_list = new ArrayList<String>(Arrays.asList(new String[] {"单独参加工伤保险"}));
//			allOptions.put("remark_list", remark_list);
//
//			srcWordPath += "南京市工伤待遇核定申报表.xml";
//		}else if("1".equals(wordType)) {
//			//发放方式
//			List<String> distributionMethod_list = new ArrayList<String>(Arrays.asList(new String[] {"单位发放", "市民卡发放"}));
//			allOptions.put("distributionMethod_list", distributionMethod_list);
//
//			//备注
//			List<String> remark_list = new ArrayList<String>(Arrays.asList(new String[] {"第三方责任", null, "补缴工伤保险费", null, "单独参加工伤保险"}));
//			allOptions.put("remark_list", remark_list);
//
//			srcWordPath += "南京市工伤医疗费用核报申报表.xml";
//		}else if("2".equals(wordType)) {
//			srcWordPath += "南京市就业登记人员花名册.xml";
//		}else if("3".equals(wordType)) {
////			生育分类
//			List<String> fertilityType_list = new ArrayList<String>(Arrays.asList(new String[] {"顺产", "  助娩产", "  剖宫产", null, "2月以下妊娠流产", null, "2-3月妊娠流产", null, "3-7月妊娠流产", null, "上取环", "  绝育手术", "  护理假"}));
//			allOptions.put("fertilityType_list", fertilityType_list);
//
////			晚婚晚育
//			List<String> lateChildbirth_list = new ArrayList<String>(Arrays.asList(new String[] {"是", "  否"}));
//			allOptions.put("lateChildbirth_list", lateChildbirth_list);
//
////			是否第二胎
//			List<String> secondChild_list = new ArrayList<String>(Arrays.asList(new String[] {"是", "  否"}));
//			allOptions.put("secondChild_list", secondChild_list);
//
//			List<String> remarks = new ArrayList<String>(Arrays.asList(new String[] {"单独参加工伤保险"}));
//			allOptions.put("remark_list", remarks);
//
//			srcWordPath += "南京市生育保险待遇申报表.xml";
//		}else if("4".equals(wordType)) {
////			单位性质
//			List<String> unitNature_list = new ArrayList<String>(Arrays.asList(new String[] {"企业", "机关", "事业单位", "社会团体", "民办非企业", "律师事务所", null, "会计事务所", "个体工商户", "特殊单位"}));
//			allOptions.put("unitNature_list", unitNature_list);
////			事业单位经费来源
//			List<String> fundSources_list = new ArrayList<String>(Arrays.asList(new String[] {"全额拨款", "差额拨款", "自收自支"}));
//			allOptions.put("fundSources_list", fundSources_list);
//
//			srcWordPath += "南京市用人单位社会保险信息采集表.xml";
//		}else if("5".equals(wordType)) {
//			srcWordPath += "南京市职工社会保险登记花名册.xml";
//		}else if("6".equals(wordType)) {
//			srcWordPath += "退费申请表.xml";
//		}else if("7".equals(wordType)) {
//			srcWordPath += "终止、解除劳动关系及社会保险关系变更申报花名册.xml";
//		}
        //文件保存路径
        String wordPath = exportWordPath + "/file";
        //文件访问路径
        String wordUrl = exportWordUrl + "/file";

        WordXmlBean wordXmlBean = new WordXmlBean();
        wordXmlBean.setSrcWordPath(srcWordPath);
        wordXmlBean.setAllOptions(allOptions);
        wordXmlBean.setWordPath(wordPath);
        wordXmlBean.setWordUrl(wordUrl);
        return wordXmlBean;
    }

    private static List<Integer> toArray(Object value) {
        if (value == null || StringUtils.isBlank(value.toString())) {
            return null;
        }
        List<Integer> checkedOptionList = new ArrayList<Integer>();
        String[] values = value.toString().split(",");
        for (String v : values) {
            try {
                checkedOptionList.add(Integer.parseInt(v));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return checkedOptionList;
    }

    public static void generateWord(String srcWord, String targetWordPath, String fileName, Map<String, Object> dynamicVariables, Map<String, List<String>> allOptions, String wordType) {
//	public static void generateWord(String srcWord, String targetWordPath, String fileName, Map<String,Object> dynamicVariables, Map<String, List<String>> allOptions, Map<String, List<Integer>> checkedOptions, String wordType) {
        try {
            FileUtil.copyFile(srcWord, targetWordPath, fileName + ".xml");

            String xmlPath = targetWordPath + "/" + fileName + ".xml";
            String wordPath = targetWordPath + "/" + fileName + ".docx";

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setIgnoringElementContentWhitespace(false);

            try {

                DocumentBuilder db = dbf.newDocumentBuilder();
                Document xmldoc = db.parse(xmlPath);

                Element root = xmldoc.getDocumentElement();

                NodeList booklist = root.getElementsByTagName("w:r");

                for (int i = 0; i < booklist.getLength(); i++) {
                    Element ele = (Element) booklist.item(i);
                    NodeList childNodes = ele.getChildNodes();
                    for (int j = 0; j < childNodes.getLength(); j++) {
                        Node n = childNodes.item(j);
                        String oldValue = n.getTextContent();
                        String newValue = oldValue;
//	                  boolean stop = false;
                        if (StringUtils.isNotBlank(newValue)) {
                            boolean hasVariable = false;
                            if (StringUtils.isNotBlank(newValue) && newValue.indexOf("${") >= 0) {
                                Pattern p = Pattern.compile("(\\$\\{[^\\}]+})");
                                Matcher matcher = p.matcher(newValue);
                                while (matcher.find()) {
                                    String key = matcher.group(1);
                                    String key2 = key.substring(2, key.length() - 1);
                                    if (dynamicVariables.get(key2) != null) {
                                        hasVariable = true;
                                        newValue = newValue.replace(key, dynamicVariables.get(key2).toString());
                                    } else {
                                        hasVariable = true;
                                        newValue = newValue.replace(key, "");
                                    }
                                }
                            }

                            if (hasVariable) {
                                NodeList colorNodes = ele.getElementsByTagName("w:color");
                                for (int k = 0; k < colorNodes.getLength(); k++) {
                                    Node colorNode = colorNodes.item(k);
                                    NamedNodeMap attributes = colorNode.getAttributes();
                                    for (int l = 0; l < attributes.getLength(); l++) {
                                        attributes.item(l).setNodeValue("000000");
                                    }
                                }
                                n.setTextContent(newValue);
                                System.out.println(oldValue + " >>> " + newValue);
                            }
//						System.out.println(newValue);
                            if (StringUtils.isNotBlank(newValue) && newValue.startsWith("#{") && newValue.endsWith("}")) {
//							stop = true;
                                String key = newValue.substring(2, newValue.length() - 1);

                                //选项值
                                List<String> options = allOptions.get(key);
                                //选中的选项
                                List<Integer> checkedOptionList = toArray(dynamicVariables.get(key));
//							List<Integer> checkedOptionList = checkedOptions.get(key);

                                if (options != null) {

                                    Node parentE_wp = ele.getParentNode();
                                    //下一个节点，若有下一个节点，则在下一个节点前添加，否则在父节点末尾添加
                                    Node nextE1 = ele.getNextSibling();
                                    Node nextE2 = parentE_wp.getNextSibling();

//								Node wtcParent = parentE_wp.getParentNode();
//								wtcParent.removeChild(parentE_wp);
                                    parentE_wp.removeChild(ele);


//								Element wp = getWPElement(xmldoc, wordType);
                                    Element wp = null;
                                    int index = -1;
                                    //是否为下一个换行
                                    boolean isNextP = false;
//								boolean isFirst = true;
                                    for (String option : options) {
                                        if (option == null) {
                                            if (isNextP) {
                                                if (nextE2 != null) {
                                                    parentE_wp.getParentNode().insertBefore(wp, nextE2);
                                                } else {
                                                    parentE_wp.getParentNode().appendChild(wp);
                                                }
                                            }
                                            isNextP = true;
                                            wp = getWPElement(xmldoc, wordType);
                                            continue;
                                        }
                                        index++;
                                        boolean checked = false;
                                        if (checkedOptionList != null && checkedOptionList.contains(index)) {
                                            checked = true;
                                        }
                                        //勾选框
                                        Element wr1 = getCheckBoxElement(xmldoc, checked, wordType);
                                        //选项值
                                        Element wr2 = getCheckValueElement(xmldoc, option, wordType);
                                        if (isNextP) {
                                            if ("3".equals(wordType)) {
                                                wp.appendChild(wr2);
                                                wp.appendChild(wr1);
                                            } else {
                                                wp.appendChild(wr1);
                                                wp.appendChild(wr2);
                                            }
                                        } else {
                                            if (nextE1 != null) {
                                                if ("3".equals(wordType)) {
                                                    parentE_wp.insertBefore(wr2, nextE1);
                                                    parentE_wp.insertBefore(wr1, nextE1);
                                                } else {
                                                    parentE_wp.insertBefore(wr1, nextE1);
                                                    parentE_wp.insertBefore(wr2, nextE1);
                                                }
                                            } else {
                                                if ("3".equals(wordType)) {
                                                    parentE_wp.appendChild(wr2);
                                                    parentE_wp.appendChild(wr1);
                                                } else {
                                                    parentE_wp.appendChild(wr1);
                                                    parentE_wp.appendChild(wr2);
                                                }
                                            }
                                        }
                                    }
                                    if (isNextP) {
                                        if (nextE2 != null) {
                                            parentE_wp.getParentNode().insertBefore(wp, nextE2);
                                        } else {
                                            parentE_wp.getParentNode().appendChild(wp);
                                        }
                                    }
                                } else {
                                    n.setTextContent("");
                                }
                            }
                        }
//	                  if(stop) {
//	                	  break;
//	                  }

                    }
                }

                if ("0".equals(wordType)) {
                    //生成表格数据列
                    createTable_0(xmldoc, dynamicVariables);
                } else if ("2".equals(wordType)) {
                    //生成表格数据列
                    createTable_2(xmldoc, dynamicVariables);
                } else if ("4".equals(wordType)) {
                    //生成表格数据列
                    checkInsuranceType(xmldoc, dynamicVariables);
                } else if ("5".equals(wordType)) {
                    //生成表格数据列
                    createTable_5(xmldoc, dynamicVariables);//
                }
                //保存
                TransformerFactory factory = TransformerFactory.newInstance();
                Transformer former = factory.newTransformer();

                former.transform(new DOMSource(xmldoc), new StreamResult(new File(xmlPath)));

//	            com.spire.doc.Document doc = new com.spire.doc.Document();
//	            doc.loadFromFile(xmlPath);
//	            doc.saveToFile(wordPath, FileFormat.Docx);
//	            doc.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    public static Element getWPElement(Document xmldoc, String wordType) {
        Element wp = xmldoc.createElement("w:p");
        if ("3".equals(wordType)) {
            wp.setAttribute("w:rsidR", "003A0B0B");
            wp.setAttribute("w:rsidRDefault", "00B85159");
        } else {
            wp.setAttribute("w:rsidR", "00AA2EEC");
            wp.setAttribute("w:rsidRDefault", "00AA2EEC");
            wp.setAttribute("w:rsidP", "00AA2EEC");

            Element w_ppr = xmldoc.createElement("w:pPr");

            Element spacing = xmldoc.createElement("w:spacing");
            spacing.setAttribute("w:line", "300");
            spacing.setAttribute("w:lineRule", "exact");
            w_ppr.appendChild(spacing);

            Element wrpr = xmldoc.createElement("w:rPr");
            Element wrpr_rFonts = xmldoc.createElement("w:rFonts");
            wrpr_rFonts.setAttribute("w:ascii", "宋体");
            wrpr_rFonts.setAttribute("w:hAnsi", "宋体");
            wrpr.appendChild(wrpr_rFonts);

            Element wrpr_kern = xmldoc.createElement("w:kern");
            wrpr_kern.setAttribute("w:val", "0");
            Element wrpr_sz = xmldoc.createElement("w:sz");
            wrpr_sz.setAttribute("w:val", "24");
            Element wrpr_szCs = xmldoc.createElement("w:szCs");
            wrpr_szCs.setAttribute("w:val", "22");
            w_ppr.appendChild(wrpr);
            wp.appendChild(w_ppr);
        }
        return wp;
    }

    public static Element getCheckBoxElement(Document xmldoc, boolean checked, String wordType) {
//		字体
        String typeface = "宋体";
//		字体大小
        String typeSize = "32";
        if ("3".equals(wordType)) {
            typeface = "方正准圆简体";
            typeSize = "17";
        } else if ("4".equals(wordType)) {
            typeSize = "21";
        }
        Element wr = xmldoc.createElement("w:r");
        Element wrpr = xmldoc.createElement("w:rPr");
        Element wrpr_rFonts = xmldoc.createElement("w:rFonts");
        wrpr_rFonts.setAttribute("w:ascii", typeface);
        wrpr_rFonts.setAttribute("w:hAnsi", typeface);
        wrpr_rFonts.setAttribute("w:hint", "eastAsia");

        Element wrpr_kern = xmldoc.createElement("w:kern");
        wrpr_kern.setAttribute("w:val", "0");
        Element wrpr_sz = xmldoc.createElement("w:sz");
        wrpr_sz.setAttribute("w:val", typeSize);
        Element wrpr_szCs = xmldoc.createElement("w:szCs");
        wrpr_szCs.setAttribute("w:val", typeSize);

        Element wsym = xmldoc.createElement("w:sym");
        wsym.setAttribute("w:font", "Wingdings 2");
        if (checked) {
            wsym.setAttribute("w:char", "0052");
        } else {
            wsym.setAttribute("w:char", "00A3");
        }
        wrpr.appendChild(wrpr_rFonts);
        wrpr.appendChild(wrpr_kern);

        if (!"4".equals(wordType)) {
            wrpr.appendChild(wrpr_sz);
        }
        wrpr.appendChild(wrpr_szCs);
        wr.appendChild(wrpr);
        wr.appendChild(wsym);
        return wr;
    }

    public static Element getCheckValueElement(Document xmldoc, String textContent, String wordType) {
//		字体
        String typeface = "宋体";

        if ("3".equals(wordType)) {
            typeface = "方正准圆简体";
        }

        //选项值
        Element wr = xmldoc.createElement("w:r");
        Element wrpr = xmldoc.createElement("w:rPr");
        Element wrpr_rFonts = xmldoc.createElement("w:rFonts");
        wrpr_rFonts.setAttribute("w:ascii", typeface);
        wrpr_rFonts.setAttribute("w:hint", "eastAsia");

        if ("3".equals(wordType)) {
            wrpr_rFonts.setAttribute("w:eastAsia", typeface);
            wrpr.appendChild(wrpr_rFonts);
        } else {//默认
            wrpr_rFonts.setAttribute("w:hAnsi", typeface);
            Element wrpr_kern = xmldoc.createElement("w:kern");
            wrpr_kern.setAttribute("w:val", "0");
            wrpr.appendChild(wrpr_rFonts);
            wrpr.appendChild(wrpr_kern);
            if ("4".equals(wordType)) {
                Element wrpr_szCs = xmldoc.createElement("w:szCs");
                wrpr_szCs.setAttribute("w:val", "21");
                wrpr.appendChild(wrpr_szCs);
            } else {
                Element wrpr_sz = xmldoc.createElement("w:sz");
                wrpr_sz.setAttribute("w:val", "24");
                Element wrpr_szCs = xmldoc.createElement("w:szCs");
                wrpr_szCs.setAttribute("w:val", "22");
                wrpr.appendChild(wrpr_sz);
                wrpr.appendChild(wrpr_szCs);
            }
        }

        Element wt = xmldoc.createElement("w:t");
        wt.setAttribute("xml:space", "preserve");
        wt.setTextContent(textContent);

        wr.appendChild(wrpr);
        wr.appendChild(wt);
        return wr;
    }

    public static Element getCheckValueBeforeElement(Document xmldoc) {
        Element w_ppr = xmldoc.createElement("w:pPr");
        Element ppr_jc = xmldoc.createElement("w:jc");
        ppr_jc.setAttribute("w:val", "center");
        Element ppr_rPr = xmldoc.createElement("w:rPr");
        Element rPr_rFonts = xmldoc.createElement("w:rFonts");
        rPr_rFonts.setAttribute("w:ascii", "方正准圆简体");
        rPr_rFonts.setAttribute("w:eastAsia", "方正准圆简体");
        ppr_rPr.appendChild(rPr_rFonts);
        w_ppr.appendChild(ppr_jc);
        w_ppr.appendChild(ppr_rPr);
        return w_ppr;
    }

    /**
     * 生成表格数据列
     *
     * @param xmldoc
     * @param dynamicVariables
     * @return
     */
    private static void createTable_0(Document xmldoc, Map<String, Object> dynamicVariables) {
        List<List<String>> dataList = new ArrayList<List<String>>();
        if (dynamicVariables.get("productList") != null) {
            try {
                JSONArray info = JSONArray.fromObject(dynamicVariables.get("productList"));
                Iterator<JSONObject> it = info.iterator();
                while (it.hasNext()) {
                    JSONObject next = it.next();
                    //产品名称
                    String name = next.has("name") ? next.getString("name") : "";
                    //规格
                    String specification = next.has("specification") ? next.getString("specification") : "";
                    //单位
                    String unit = next.has("unit") ? next.getString("unit") : "";
                    //数量
                    String quantity = next.has("quantity") ? next.getString("quantity") : "";
                    //单价（元）
                    String unitPrice = next.has("unitPrice") ? next.getString("unitPrice") : "";
                    //总价（元）
                    String totalPrice = next.has("totalPrice") ? next.getString("totalPrice") : "";
                    //交货期限
                    String deliveryDate = next.has("deliveryDate") ? next.getString("deliveryDate") : "";
                    dataList.add(new ArrayList<String>(Arrays.asList(new String[]{name, specification, unit, quantity, unitPrice, totalPrice, deliveryDate})));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        int count = 2 - dataList.size();
        if (count > 0) {
            for (int i = 0; i < count; i++) {
                dataList.add(new ArrayList<String>(Arrays.asList(new String[]{"", "", "", "", "", "", ""})));
            }
        }

        //找出表格
        NodeList tblList = xmldoc.getElementsByTagName("w:tbl");
        if (tblList != null && tblList.getLength() > 0) {
            Element tbl = (Element) tblList.item(0);
            List<Integer> tc_wList = new ArrayList<Integer>(Arrays.asList(new Integer[]{383, 873, 664, 465, 336, 667, 604, 1008}));
            int index = 0;
            for (List<String> list : dataList) {
                index++;
                Element tr = xmldoc.createElement("w:tr");
//    			tr.setAttribute("w:rsidR", "008A142F");
//    			tr.setAttribute("w:rsidTr", "0055235C");

                Element trPr = xmldoc.createElement("w:trPr");
                Element trHeight = xmldoc.createElement("w:trHeight");
                trHeight.setAttribute("w:val", "548");
                trPr.appendChild(trHeight);
                tr.appendChild(trPr);

                for (int i = 0; i < 8; i++) {
                    Element tc = xmldoc.createElement("w:tc");

                    Element tcPr = xmldoc.createElement("w:tcPr");
                    Element tcW = xmldoc.createElement("w:tcW");
                    tcW.setAttribute("w:w", tc_wList.get(i).toString());
                    tcW.setAttribute("w:type", "pct");
                    Element vAlign = xmldoc.createElement("w:vAlign");
                    vAlign.setAttribute("w:val", "center");
                    tcPr.appendChild(tcW);
                    tcPr.appendChild(vAlign);
                    tc.appendChild(tcPr);

                    Element p = xmldoc.createElement("w:p");
//    				p.setAttribute("w:rsidR", "00BA5C1C");
//    				p.setAttribute("w:rsidRDefault", "00BA5C1C");
//    				p.setAttribute("w:rsidP", "0055235C");
//    				if(i != 0) {
//    					p.setAttribute("w:rsidRPr", "007F03EF");
//    				}

                    Element pPr = xmldoc.createElement("w:pPr");
                    Element spacing = xmldoc.createElement("w:spacing");
                    spacing.setAttribute("w:line", "440");
                    spacing.setAttribute("w:lineRule", "exact");
                    pPr.appendChild(spacing);
                    Element jc = xmldoc.createElement("w:jc");
                    jc.setAttribute("w:val", "center");
                    pPr.appendChild(jc);
                    Element rPr = xmldoc.createElement("w:rPr");
                    Element rFonts = xmldoc.createElement("w:rFonts");
                    rFonts.setAttribute("w:asciiTheme", "minorEastAsia");
                    rFonts.setAttribute("w:eastAsiaTheme", "minorEastAsia");
                    rFonts.setAttribute("w:hAnsiTheme", "minorEastAsia");
                    rFonts.setAttribute("w:cs", "Times New Roman");
                    rPr.appendChild(rFonts);
                    Element sz = xmldoc.createElement("w:szCs");
                    sz.setAttribute("w:val", "21");
                    rPr.appendChild(sz);
                    pPr.appendChild(rPr);

                    Element r = xmldoc.createElement("w:r");

                    Element r_rPr = xmldoc.createElement("w:rPr");
                    Element r_rFonts = xmldoc.createElement("w:rFonts");
                    r_rFonts.setAttribute("w:asciiTheme", "minorEastAsia");
                    r_rFonts.setAttribute("w:eastAsiaTheme", "minorEastAsia");
                    r_rFonts.setAttribute("w:hAnsiTheme", "minorEastAsia");
                    r_rFonts.setAttribute("w:cs", "Times New Roman");
                    r_rPr.appendChild(r_rFonts);
                    Element r_sz = xmldoc.createElement("w:szCs");
                    r_sz.setAttribute("w:val", "21");
                    r_rPr.appendChild(r_sz);
                    r.appendChild(r_rPr);
                    Element t = xmldoc.createElement("w:t");
                    if (i == 0) {
                        t.setTextContent(index + "");
                    } else {
                        t.setTextContent(list.get(i - 1));
                    }
                    r.appendChild(t);

                    p.appendChild(pPr);
                    p.appendChild(r);

                    tc.appendChild(tcPr);
                    tc.appendChild(p);
                    tr.appendChild(tc);
                }

                NodeList childNodes = tbl.getChildNodes();
                Node lastChild = childNodes.item(childNodes.getLength() - 1);
                tbl.removeChild(lastChild);
                tbl.appendChild(tr);
                tbl.appendChild(lastChild);
            }
        }
    }

    /**
     * 生成表格数据列
     *
     * @param xmldoc
     * @param dynamicVariables
     * @return
     */
    private static void createTable_2(Document xmldoc, Map<String, Object> dynamicVariables) {
        List<List<String>> nameList = new ArrayList<List<String>>();
        if (dynamicVariables.get("nameList") != null) {
            try {
                JSONArray info = JSONArray.fromObject(dynamicVariables.get("nameList"));
                Iterator<JSONObject> it = info.iterator();
                while (it.hasNext()) {
                    JSONObject next = it.next();
                    //姓名
                    String name = next.has("name") ? next.getString("name") : "";
                    //性别
                    String sex = next.has("sex") ? next.getString("sex") : "";
                    //社会保障卡号
                    String cardNo = next.has("cardNo") ? next.getString("cardNo") : "";
                    //就业创业证号
                    String certificateNo = next.has("certificateNo") ? next.getString("certificateNo") : "";
                    //文化程度
                    String educationLevel = next.has("educationLevel") ? next.getString("educationLevel") : "";
                    //岗位（工种）
                    String postion = next.has("postion") ? next.getString("postion") : "";
                    //劳动合同开始日期
                    String startDate = next.has("startDate") ? next.getString("startDate") : "";
                    //劳动合同结束日期
                    String endDate = next.has("endDate") ? next.getString("endDate") : "";
                    //是否留学归国人员
                    String overseasStudy = next.has("overseasStudy") ? next.getString("overseasStudy") : "";
                    //备注
                    String remark = next.has("remark") ? next.getString("remark") : "";
                    nameList.add(new ArrayList<String>(Arrays.asList(new String[]{name, sex, cardNo, certificateNo, educationLevel, postion, startDate, endDate, overseasStudy, remark})));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        int count = 10 - nameList.size();
        if (count > 0) {
            for (int i = 0; i < count; i++) {
                nameList.add(new ArrayList<String>(Arrays.asList(new String[]{"", "", "", "", "", "", "", "", "", ""})));
            }
        }

        //找出表格
        NodeList tblList = xmldoc.getElementsByTagName("w:tbl");
        if (tblList != null && tblList.getLength() > 0) {
            Element tbl = (Element) tblList.item(0);
            List<Integer> tc_wList = new ArrayList<Integer>(Arrays.asList(new Integer[]{644, 1084, 720, 1800, 2775, 850, 1847, 1185, 1155, 1096, 1096}));
            int index = 0;
            for (List<String> list : nameList) {
                index++;
                Element tr = xmldoc.createElement("w:tr");
                tr.setAttribute("w:rsidR", "00BA5C1C");
                tr.setAttribute("w:rsidTr", "0055235C");

                Element trPr = xmldoc.createElement("w:trPr");
                Element trHeight = xmldoc.createElement("w:trHeight");
                trHeight.setAttribute("w:val", "540");
                trPr.appendChild(trHeight);
                tr.appendChild(trPr);

                for (int i = 0; i < 11; i++) {
                    Element tc = xmldoc.createElement("w:tc");

                    Element tcPr = xmldoc.createElement("w:tcPr");
                    Element tcW = xmldoc.createElement("w:tcW");
                    tcW.setAttribute("w:w", tc_wList.get(i).toString());
                    tcW.setAttribute("w:type", "dxa");
                    Element vAlign = xmldoc.createElement("w:vAlign");
                    vAlign.setAttribute("w:val", "center");
                    tcPr.appendChild(tcW);
                    tcPr.appendChild(vAlign);
                    tc.appendChild(tcPr);

                    Element p = xmldoc.createElement("w:p");
                    p.setAttribute("w:rsidR", "00BA5C1C");
                    p.setAttribute("w:rsidRDefault", "00BA5C1C");
                    p.setAttribute("w:rsidP", "0055235C");
                    if (i != 0) {
                        p.setAttribute("w:rsidRPr", "007F03EF");
                    }

                    Element pPr = xmldoc.createElement("w:pPr");
                    Element spacing = xmldoc.createElement("w:spacing");
                    spacing.setAttribute("w:line", "360");
                    spacing.setAttribute("w:lineRule", "auto");
                    pPr.appendChild(spacing);
                    Element jc = xmldoc.createElement("w:jc");
                    jc.setAttribute("w:val", "center");
                    pPr.appendChild(jc);
                    Element rPr = xmldoc.createElement("w:rPr");
                    Element rFonts = xmldoc.createElement("w:rFonts");
                    rFonts.setAttribute("w:ascii", "仿宋_GB2312");
                    rFonts.setAttribute("w:eastAsia", "仿宋_GB2312");
                    rPr.appendChild(rFonts);
                    Element sz = xmldoc.createElement("w:sz");
                    sz.setAttribute("w:val", "24");
                    rPr.appendChild(sz);
                    pPr.appendChild(rPr);

                    Element r = xmldoc.createElement("w:r");

                    Element r_rPr = xmldoc.createElement("w:rPr");
                    Element r_rFonts = xmldoc.createElement("w:rFonts");
                    r_rFonts.setAttribute("w:ascii", "仿宋_GB2312");
                    r_rFonts.setAttribute("w:eastAsia", "仿宋_GB2312");
                    r_rFonts.setAttribute("w:hint", "eastAsia");
                    r_rPr.appendChild(r_rFonts);
                    Element r_sz = xmldoc.createElement("w:sz");
                    r_sz.setAttribute("w:val", "24");
                    r_rPr.appendChild(r_sz);
                    r.appendChild(r_rPr);
                    Element t = xmldoc.createElement("w:t");
                    if (i == 0) {
                        t.setTextContent(index + "");
                    } else {
                        t.setTextContent(list.get(i - 1));
                    }
                    r.appendChild(t);

                    p.appendChild(pPr);
                    p.appendChild(r);

                    tc.appendChild(tcPr);
                    tc.appendChild(p);
                    tr.appendChild(tc);
                }

                tbl.appendChild(tr);
            }
        }
    }

    /**
     * 生成表格数据列
     *
     * @param xmldoc
     * @param dynamicVariables
     * @return
     */
    private static void createTable_5(Document xmldoc, Map<String, Object> dynamicVariables) {
        List<List<String>> nameList = new ArrayList<List<String>>();
        if (dynamicVariables.get("nameList") != null) {
            try {
                JSONArray info = JSONArray.fromObject(dynamicVariables.get("nameList"));
                Iterator<JSONObject> it = info.iterator();
                while (it.hasNext()) {
                    JSONObject next = it.next();
                    //姓名
                    String name = next.has("name") ? next.getString("name") : "";
                    //社会保障卡号
                    String cardNo = next.has("cardNo") ? next.getString("cardNo") : "";
                    //身份证号码
                    String idNo = next.has("idNo") ? next.getString("idNo") : "";
                    //合同类型
                    String contractType = next.has("contractType") ? next.getString("contractType") : "";
                    //合同起止时间
                    String startStopTime = next.has("startStopTime") ? next.getString("startStopTime") : "";
                    //岗位
                    String postion = next.has("postion") ? next.getString("postion") : "";
                    //文化程度
                    String educationLevel = next.has("educationLevel") ? next.getString("educationLevel") : "";
                    //参保时间
                    String insuredTime = next.has("insuredTime") ? next.getString("insuredTime") : "";
                    //缴费基数
                    String paymentBase = next.has("paymentBase") ? next.getString("paymentBase") : "";
                    //备注
                    String remark = next.has("remark") ? next.getString("remark") : "";
                    nameList.add(new ArrayList<String>(Arrays.asList(new String[]{name, cardNo, idNo, contractType, startStopTime, postion, educationLevel, insuredTime, paymentBase, remark})));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        int count = 10 - nameList.size();
        if (count > 0) {
            for (int i = 0; i < count; i++) {
                nameList.add(new ArrayList<String>(Arrays.asList(new String[]{"", "", "", "", "", "", "", "", "", ""})));
            }
        }

        //找出表格
        NodeList tblList = xmldoc.getElementsByTagName("w:tbl");
        if (tblList != null && tblList.getLength() > 0) {
            Element tbl = (Element) tblList.item(0);
            List<Integer> tc_wList = new ArrayList<Integer>(Arrays.asList(new Integer[]{456, 931, 1733, 2946, 1184, 2326, 868, 646, 1183, 1125, 1305}));
            int index = 0;
            for (List<String> list : nameList) {
                index++;
                Element tr = xmldoc.createElement("w:tr");
                tr.setAttribute("w:rsidR", "00BA5C1C");

                Element trPr = xmldoc.createElement("w:trPr");
                Element trHeight = xmldoc.createElement("w:trHeight");
                trHeight.setAttribute("w:val", "493");
                trPr.appendChild(trHeight);
                Element trPr_jc = xmldoc.createElement("w:jc");
                trPr_jc.setAttribute("w:val", "center");
                trPr.appendChild(trPr_jc);
                tr.appendChild(trPr);

                for (int i = 0; i < 11; i++) {
                    Element tc = xmldoc.createElement("w:tc");

                    Element tcPr = xmldoc.createElement("w:tcPr");
                    Element tcW = xmldoc.createElement("w:tcW");
                    tcW.setAttribute("w:w", tc_wList.get(i).toString());
                    tcW.setAttribute("w:type", "dxa");
                    tcPr.appendChild(tcW);
                    tc.appendChild(tcPr);

                    Element p = xmldoc.createElement("w:p");
                    p.setAttribute("w:rsidR", "00420FA5");
                    p.setAttribute("w:rsidRDefault", "007B1C4F");

                    Element pPr = xmldoc.createElement("w:pPr");
                    Element jc = xmldoc.createElement("w:jc");
                    jc.setAttribute("w:val", "center");
                    pPr.appendChild(jc);
                    Element rPr = xmldoc.createElement("w:rPr");
                    pPr.appendChild(rPr);

                    Element r = xmldoc.createElement("w:r");

                    Element r_rPr = xmldoc.createElement("w:rPr");
                    Element r_rFonts = xmldoc.createElement("w:rFonts");
                    r_rFonts.setAttribute("w:hint", "eastAsia");
                    r_rPr.appendChild(r_rFonts);
                    r.appendChild(r_rPr);
                    Element t = xmldoc.createElement("w:t");
                    if (i == 0) {
                        t.setTextContent(index + "");
                    } else {
                        t.setTextContent(list.get(i - 1));
                    }
                    r.appendChild(t);

                    p.appendChild(pPr);
                    p.appendChild(r);

                    tc.appendChild(tcPr);
                    tc.appendChild(p);
                    tr.appendChild(tc);
                }

                tbl.appendChild(tr);
            }
        }
    }

    /**
     * 勾选险种
     *
     * @param xmldoc
     * @param dynamicVariables 选中的险种
     */
    private static void checkInsuranceType(Document xmldoc, Map<String, Object> dynamicVariables) {
        List<Integer> checkedOptionList = toArray(dynamicVariables.get("insuranceType_list"));
        if (checkedOptionList == null || checkedOptionList.size() == 0) {
            return;
        }
        //找出表格
        NodeList tblList = xmldoc.getElementsByTagName("w:tbl");
        if (tblList == null || tblList.getLength() == 0) {
            return;
        }
        Element tbl = (Element) tblList.item(0);
        NodeList trList = tbl.getElementsByTagName("w:tr");
        if (trList.getLength() < 2) {
            return;
        }
        NodeList pList = ((Element) trList.item(trList.getLength() - 2)).getElementsByTagName("w:p");
        for (int i = 0; i < pList.getLength(); i++) {
            if (!checkedOptionList.contains(i)) {
                continue;
            }
            Element p = (Element) pList.item(i);
            Element r = xmldoc.createElement("w:r");
            r.setAttribute("w:rsidRPr", "00A74F32");
            Element rpr = xmldoc.createElement("w:rPr");
            Element rpr_rFonts = xmldoc.createElement("w:rFonts");
            rpr_rFonts.setAttribute("w:ascii", "宋体");
            rpr.appendChild(rpr_rFonts);
            Element sym = xmldoc.createElement("w:sym");
            sym.setAttribute("w:font", "Wingdings 2");
            sym.setAttribute("w:char", "F050");
            r.appendChild(rpr);
            r.appendChild(sym);
            p.appendChild(r);
        }
    }

    public static void main(String[] args) {
//		String srcWord = "/Users/littleqiqi/Desktop/tmp/表单/xml/南京市工伤待遇核定申报表.xml";0,1
//		String targetWordPath = "/Users/littleqiqi/Desktop/tmp/表单/xml/111";
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//		String fileName = new File(srcWord).getName();
//		fileName = fileName.substring(0, fileName.lastIndexOf("."));
//		fileName += "_" + sdf.format(new Date())+"_"+UUID.randomUUID().toString().replaceAll("-", "").substring(0,6)+".xml";
//
//
//
//		Map<String, Object> dynamicVariables =  new HashMap<String, Object>();
//		dynamicVariables.put("fullname", "思思同学");
//		dynamicVariables.put("phoneNum", "13900000001");
//
//		//全部多选
//		Map<String, List<String>> allOptions = new HashMap<String, List<String>>();
//		//选中的序号
//		Map<String, List<Integer>> checkedOptions = new HashMap<String, List<Integer>>();
//
//		List<String> typeOs = new ArrayList<String>(Arrays.asList(new String[] {"一次性伤残补助金", "一次性工伤医疗补助金", "一次性工亡补助金", null, "1-4级人员定期待遇", "供养亲属抚恤金", "丧葬补助金", "其它"}));
//		List<Integer> typeIs = new ArrayList<Integer>(Arrays.asList(new Integer[] {1, 2, 5}));
//
//		allOptions.put("serviceType", typeOs);
//		checkedOptions.put("serviceType", typeIs);

    }

}
